package fcrypt

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"encoding/base64"
	"fmt"
)

//rsa数字签名

func RSASign(data []byte, file string) (string, error) {
	hashByte := HashByte(crypto.SHA512, string(data))
	privateKey, err := ReadPrivateKey(file)
	if err != nil {
		fmt.Println("read private key err = ", err)
		return "", err
	}
	signByte, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA512, hashByte)
	if err != nil {
		fmt.Println("rsa sign err = ", err)
		return "", err
	}

	return base64.StdEncoding.EncodeToString(signByte), nil
}

func RSAVerify(data []byte, base64str, file string) error {
	signByte, err := base64.StdEncoding.DecodeString(base64str)
	if err != nil {
		return err
	}
	hashByte := HashByte(crypto.SHA512, string(data))
	publicKey, err := ReadPublicKey(file)
	if err != nil {
		fmt.Println("read private key err = ", err)
		return err
	}
	return rsa.VerifyPKCS1v15(publicKey, crypto.SHA512, hashByte, signByte)
}
